<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 页面标题 -->
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900">{{ $t('post.createTitle') }}</h1>
        <p class="mt-2 text-gray-600">{{ $t('post.createDescription') }}</p>
      </div>

      <!-- 步骤指示器 -->
      <div class="mb-8">
        <nav aria-label="Progress">
          <ol class="flex items-center justify-center space-x-5">
            <li v-for="(step, index) in steps" :key="step.id" class="flex items-center">
              <div
                class="flex items-center justify-center w-8 h-8 rounded-full border-2 text-sm font-medium"
                :class="getStepClass(index)"
              >
                {{ index + 1 }}
              </div>
              <span class="ml-2 text-sm font-medium" :class="getStepTextClass(index)">
                {{ step.name }}
              </span>
              <div v-if="index < steps.length - 1" class="ml-5 w-5 h-px bg-gray-300"></div>
            </li>
          </ol>
        </nav>
      </div>

      <!-- 表单内容 -->
      <div class="bg-white shadow rounded-lg">
        <form @submit.prevent="handleSubmit">
          <!-- 步骤1: 宠物基本信息 -->
          <div v-show="currentStep === 0" class="p-6 space-y-6">
            <h2 class="text-lg font-medium text-gray-900 mb-4">{{ $t('post.steps.petInfo') }}</h2>

            <!-- 选择模式 -->
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
              <h3 class="text-sm font-medium text-gray-900 mb-3">{{ $t('post.selectPetMode') }}</h3>
              <div class="flex space-x-4">
                <label class="flex items-center">
                  <input
                    v-model="petMode"
                    type="radio"
                    value="existing"
                    class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300"
                  />
                  <span class="ml-2 text-sm text-gray-700">{{ $t('post.selectExistingPet') }}</span>
                </label>
                <label class="flex items-center">
                  <input
                    v-model="petMode"
                    type="radio"
                    value="new"
                    class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300"
                  />
                  <span class="ml-2 text-sm text-gray-700">{{ $t('post.createNewPet') }}</span>
                </label>
              </div>
            </div>

            <!-- 选择已有宠物 -->
            <div v-if="petMode === 'existing'" class="space-y-4">
              <div v-if="loadingPets" class="text-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600 mx-auto"></div>
                <p class="mt-2 text-sm text-gray-600">{{ $t('common.loading') }}</p>
              </div>

              <div v-else-if="userPets.length === 0" class="text-center py-8">
                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                </svg>
                <h3 class="mt-2 text-sm font-medium text-gray-900">{{ $t('post.noPetsYet') }}</h3>
                <p class="mt-1 text-sm text-gray-500">{{ $t('post.noPetsHint') }}</p>
                <div class="mt-4">
                  <button
                    type="button"
                    @click="petMode = 'new'"
                    class="btn-primary"
                  >
                    {{ $t('post.createNewPet') }}
                  </button>
                </div>
              </div>

              <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div
                  v-for="pet in userPets"
                  :key="pet.id"
                  class="border rounded-lg p-4 cursor-pointer transition-colors"
                  :class="selectedPetId === pet.id ? 'border-primary-500 bg-primary-50' : 'border-gray-200 hover:border-gray-300'"
                  @click="selectPet(pet)"
                >
                  <div class="flex items-center space-x-3">
                    <div class="w-12 h-12 rounded-lg overflow-hidden bg-gray-200 flex-shrink-0">
                      <img
                        v-if="pet.photo_url"
                        :src="getFullImageUrl(pet.photo_url)"
                        :alt="pet.name"
                        class="w-full h-full object-cover"
                      />
                      <div v-else class="w-full h-full flex items-center justify-center">
                        <svg class="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                        </svg>
                      </div>
                    </div>
                    <div class="flex-1 min-w-0">
                      <h4 class="text-sm font-medium text-gray-900 truncate">{{ pet.name || $t('post.hints.unnamedPet') }}</h4>
                      <p class="text-sm text-gray-500">{{ pet.species }} · {{ pet.color }}</p>
                      <p v-if="pet.breed" class="text-xs text-gray-400">{{ pet.breed }}</p>
                    </div>
                    <div v-if="selectedPetId === pet.id" class="flex-shrink-0">
                      <svg class="h-5 w-5 text-primary-600" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 添加新宠物表单 -->
            <div v-if="petMode === 'new'" class="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <!-- 宠物名字 -->
              <div>
                <label for="petName" class="block text-sm font-medium text-gray-700">
                  {{ $t('post.fields.petName') }} <span class="text-red-500">*</span>
                </label>
                <input
                  id="petName"
                  v-model="petForm.name"
                  type="text"
                  required
                  class="mt-1 input-field"
                  :placeholder="$t('post.placeholders.petName')"
                />
              </div>

              <!-- 宠物品种 -->
              <div>
                <label for="petSpecies" class="block text-sm font-medium text-gray-700">
                  {{ $t('post.fields.petSpecies') }} <span class="text-red-500">*</span>
                </label>
                <select
                  id="petSpecies"
                  v-model="petForm.species"
                  required
                  class="mt-1 input-field"
                >
                  <option value="">{{ $t('post.placeholders.selectSpecies') }}</option>
                  <option v-for="species in petSpeciesOptions" :key="species.value" :value="species.value">
                    {{ species.label }}
                  </option>
                </select>
              </div>

              <!-- 品种详情 -->
              <div>
                <label for="petBreed" class="block text-sm font-medium text-gray-700">
                  {{ $t('post.fields.petBreed') }}
                </label>
                <input
                  id="petBreed"
                  v-model="petForm.breed"
                  type="text"
                  class="mt-1 input-field"
                  :placeholder="$t('post.placeholders.selectBreed')"
                />
              </div>

              <!-- 主要毛色 -->
              <div>
                <label for="petColor" class="block text-sm font-medium text-gray-700">
                  {{ $t('post.fields.petColor') }} <span class="text-red-500">*</span>
                </label>
                <input
                  id="petColor"
                  v-model="petForm.color"
                  type="text"
                  required
                  class="mt-1 input-field"
                  :placeholder="$t('post.placeholders.enterColor')"
                />
              </div>

              <!-- 性别 -->
              <div>
                <label for="petGender" class="block text-sm font-medium text-gray-700">
                  {{ $t('post.fields.petGender') }} <span class="text-red-500">*</span>
                </label>
                <select
                  id="petGender"
                  v-model="petForm.gender"
                  required
                  class="mt-1 input-field"
                >
                  <option value="">{{ $t('post.placeholders.selectGender') }}</option>
                  <option v-for="gender in petGenderOptions" :key="gender.value" :value="gender.value">
                    {{ gender.label }}
                  </option>
                </select>
              </div>

              <!-- 年龄 -->
              <div>
                <label for="petAge" class="block text-sm font-medium text-gray-700">
                  {{ $t('post.fields.petAge') }}
                </label>
                <input
                  id="petAge"
                  v-model.number="petForm.age"
                  type="number"
                  min="0"
                  max="30"
                  class="mt-1 input-field"
                  :placeholder="$t('post.placeholders.petAge')"
                />
              </div>
            </div>

            <!-- 宠物描述 -->
            <div>
              <label for="petDescription" class="block text-sm font-medium text-gray-700">
                {{ $t('post.labels.appearanceDescription') }}
              </label>
              <textarea
                id="petDescription"
                v-model="petForm.description"
                rows="3"
                class="mt-1 input-field"
                :placeholder="$t('post.placeholders.petDescription')"
              ></textarea>
            </div>

            <!-- 宠物照片 -->
            <ImageUpload
              v-model="petForm.photo"
              :label="$t('post.labels.petPhoto')"
              :required="true"
              :help-text="$t('post.labels.uploadHelpText')"
            />
          </div>

          <!-- 步骤2: 走失信息 -->
          <div v-show="currentStep === 1" class="p-6 space-y-6">
            <h2 class="text-lg font-medium text-gray-900 mb-4">{{ $t('post.steps.lostInfo') }}</h2>

            <!-- 走失时间 -->
            <div>
              <label for="lostTime" class="block text-sm font-medium text-gray-700">
                {{ $t('post.fields.lostDate') }} <span class="text-red-500">*</span>
              </label>
              <input
                id="lostTime"
                v-model="postForm.last_seen_time"
                type="datetime-local"
                required
                class="mt-1 input-field"
              />
            </div>

            <!-- 走失地点 -->
            <AddressPicker
              v-show="currentStep === 1"
              v-model="selectedAddress"
              :label="$t('post.fields.location')"
              :placeholder="$t('post.placeholders.location')"
              :required="true"
              :help-text="$t('post.help.locationText')"
            />

            <!-- 联系方式 -->
            <div>
              <label for="contactInfo" class="block text-sm font-medium text-gray-700">
                {{ $t('post.fields.contactInfoOptional') }}
              </label>
              <textarea
                id="contactInfo"
                v-model="postForm.contact_info"
                rows="2"
                class="mt-1 input-field"
                :placeholder="$t('post.placeholders.contactInfo')"
              ></textarea>
              <p class="mt-1 text-sm text-gray-500">
                {{ $t('post.hints.contactInfoHelp') }}
              </p>
            </div>

            <!-- 视频链接 -->
            <div>
              <label for="videoUrl" class="block text-sm font-medium text-gray-700">
                {{ $t('post.fields.videoUrl') }}
              </label>
              <input
                id="videoUrl"
                v-model="postForm.video_url"
                type="url"
                class="mt-1 input-field"
                :placeholder="$t('post.placeholders.videoUrl')"
              />
            </div>
          </div>

          <!-- 错误提示 -->
          <div v-if="error" class="p-6 pt-0">
            <div class="rounded-md bg-red-50 p-4">
              <div class="flex">
                <div class="flex-shrink-0">
                  <ExclamationTriangleIcon class="h-5 w-5 text-red-400" />
                </div>
                <div class="ml-3">
                  <h3 class="text-sm font-medium text-red-800">
                    {{ error }}
                  </h3>
                </div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="px-6 py-4 bg-gray-50 flex justify-between">
            <button
              v-if="currentStep > 0"
              type="button"
              @click="previousStep"
              class="btn-secondary"
            >
              {{ $t('common.previousStep') }}
            </button>
            <div v-else></div>

            <div class="flex space-x-3">
              <router-link
                to="/"
                class="btn-secondary"
              >
                {{ $t('post.actions.cancel') }}
              </router-link>

              <button
                v-if="currentStep < steps.length - 1"
                type="button"
                @click="nextStep"
                :disabled="!canProceedToNext"
                class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {{ $t('post.actions.nextStep') }}
              </button>

              <button
                v-else
                type="submit"
                :disabled="loading || !canSubmit"
                class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <span v-if="loading" class="flex items-center">
                  <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  {{ $t('post.actions.publishing') }}
                </span>
                <span v-else>{{ $t('post.actions.publishInfo') }}</span>
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { useAuthStore } from '@/stores/auth'
import { petService } from '@/services/pets'
import { postService } from '@/services/posts'
import { getFullImageUrl } from '@/utils/helpers'
import ImageUpload from '@/components/ImageUpload.vue'
import AddressPicker from '@/components/AddressPicker.vue'
import type { Pet, PetFormData, PostFormData } from '@/types'
import { usePetSpeciesOptions, usePetGenderOptions } from '@/utils/i18n-options'

const router = useRouter()
const authStore = useAuthStore()
const { t } = useI18n()

// 步骤定义
const steps = [
  { id: 1, name: t('post.steps.petInfo') },
  { id: 2, name: t('post.steps.lostInfo') },
]

const currentStep = ref(0)
const loading = ref(false)
const error = ref('')

// 宠物选择模式
const petMode = ref<'existing' | 'new'>('existing')
const loadingPets = ref(false)
const userPets = ref<Pet[]>([])
const selectedPetId = ref<number | null>(null)

// 表单数据
const petForm = ref<PetFormData>({
  name: '',
  species: '',
  breed: '',
  color: '',
  gender: 'unknown',
  age: undefined,
  description: '',
  photo: null,
})

const postForm = ref<PostFormData>({
  pet_id: 0,
  last_seen_location: '',
  last_seen_time: '',
  video_url: '',
  contact_info: '',
})

const selectedAddress = ref<string>('')

// 计算属性
const getStepClass = (index: number) => {
  if (index < currentStep.value) {
    return 'bg-primary-600 border-primary-600 text-white'
  } else if (index === currentStep.value) {
    return 'bg-white border-primary-600 text-primary-600'
  } else {
    return 'bg-white border-gray-300 text-gray-500'
  }
}

const getStepTextClass = (index: number) => {
  if (index <= currentStep.value) {
    return 'text-primary-600'
  } else {
    return 'text-gray-500'
  }
}

const canProceedToNext = computed(() => {
  if (currentStep.value === 0) {
    if (petMode.value === 'existing') {
      return selectedPetId.value !== null
    } else {
      return petForm.value.name &&
             petForm.value.species &&
             petForm.value.color &&
             petForm.value.gender &&
             petForm.value.photo
    }
  }
  return true
})

const canSubmit = computed(() => {
  return canProceedToNext.value &&
         postForm.value.last_seen_time &&
         selectedAddress.value.trim()
})

// 国际化选项
const petSpeciesOptions = computed(() => usePetSpeciesOptions())
const petGenderOptions = computed(() => usePetGenderOptions())

// 方法
const nextStep = () => {
  if (canProceedToNext.value && currentStep.value < steps.length - 1) {
    currentStep.value++
  }
}

const previousStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 获取用户宠物列表
const fetchUserPets = async () => {
  try {
    loadingPets.value = true
    const response = await petService.getMyPets({ page: 1, limit: 50 })

    if (response.success && response.data) {
      userPets.value = response.data
      // 如果有宠物，默认选择第一个
      if (userPets.value.length > 0 && !selectedPetId.value) {
        selectedPetId.value = userPets.value[0].id
      }
    }
  } catch (err) {
    console.error('获取宠物列表失败:', err)
    // 如果获取失败，切换到新建模式
    petMode.value = 'new'
  } finally {
    loadingPets.value = false
  }
}

// 选择宠物
const selectPet = (pet: Pet) => {
  selectedPetId.value = pet.id
}

const handleSubmit = async () => {
  if (!canSubmit.value) return

  try {
    loading.value = true
    error.value = ''

    let petId: number

    if (petMode.value === 'existing') {
      // 使用已选择的宠物
      if (!selectedPetId.value) {
        throw new Error(t('post.errors.selectPet'))
      }
      petId = selectedPetId.value
    } else {
      // 创建新宠物
      const petResponse = await petService.create(petForm.value)

      if (!petResponse.success || !petResponse.data) {
        throw new Error(petResponse.message || t('post.errors.createPetFailed'))
      }
      petId = petResponse.data.id
    }

    // 创建帖子
    const postData: PostFormData = {
      pet_id: petId,
      last_seen_location: selectedAddress.value,
      last_seen_time: postForm.value.last_seen_time,
      video_url: postForm.value.video_url || undefined,
      contact_info: postForm.value.contact_info || undefined,
    }

    const postResponse = await postService.create(postData)

    if (!postResponse.success) {
      throw new Error(postResponse.message || t('post.errors.createPostFailed'))
    }

    // 成功后跳转到仪表板的我的帖子页面
    router.push('/dashboard?tab=posts')

  } catch (err: any) {
    console.error('发布失败:', err)
    error.value = err.message || t('post.errors.publishFailedRetry')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  // 检查用户是否已登录
  if (!authStore.isAuthenticated) {
    router.push('/login')
    return
  }

  // 获取用户宠物列表
  await fetchUserPets()

  // 如果没有宠物，默认切换到新建模式
  if (userPets.value.length === 0) {
    petMode.value = 'new'
  }
})
</script>
